import matplotlib.pyplot as plt
from matplotlib import image as mpimg
from matplotlib.patches import Rectangle
from matplotlib.offsetbox import AnchoredText

# 假设我们有以下数据
rows = [
    ['Alicedfsdfds\nafdsfddfasfs', 30, 'New York'],
    ['Bob', 25, 'Los Angeles'],
    ['Charlie', 35, 'Chicago'],
    [],
    ['Charlie', 35, 'Chicago'],
]

# 创建画布和子图
x_size = 240 / 25.4 / 10
y_size = 140 / 25.4 / 10

fig, ax = plt.subplots(figsize=(x_size * 10, y_size * 10), constrained_layout=True)
plt.subplots_adjust(left=0, right=1, bottom=0, top=1, wspace=None, hspace=None)

# 设置列宽和行高 140*240
column_widths = [x_size * 0.4, x_size * 0.2, x_size * 0.4]  # 相对于子图宽度的比例 三行
row_height = y_size / 5  # 相对于子图高度的比例 5列
y_offset = y_size  # 初始y偏移量，用于调整表格位置

# 绘制单元格和文本
for i, row in enumerate(rows):
    y = y_offset - i * row_height
    if len(row) == 0:
        x = 0
        for column_width in column_widths:
            x += column_width
            # 绘制单元格（矩形）
        img = mpimg.imread('../../static/data_2405160001075187.ico')
        imgplot = ax.imshow(img, extent=[0, x, y - row_height, y], aspect='auto')
        rect = Rectangle(xy=(0, y - row_height), width=x, height=row_height,
                         edgecolor='black', facecolor='none')
        ax.add_patch(rect)
        # img = mpimg.imread('../../static/data_2405160001075187.ico')
        # imgplot = ax.imshow(img, extent=[0, 0.6, 0, 0.7], aspect='auto')
        # rect = Rectangle(xy=(0, 0), width=0.6, height=0.7,
        #                  edgecolor='black', facecolor='none', linewidth=2)
        # ax.add_patch(rect)
        # ax.set_xlim(0, 0.7)  # 假设图片是100x100像素
        # ax.set_ylim(0, 0.3)
        # ax.set_aspect('equal')
    for j, value in enumerate(row):
        x = 0
        for jj in range(0, j):
            x += column_widths[jj]
        width = column_widths[j]

        # 绘制单元格（矩形）
        rect = Rectangle(xy=(x, y - row_height), width=width, height=row_height,
                         edgecolor='black', facecolor='none')
        ax.add_patch(rect)

        # 在单元格中添加文本
        ax.text((x + width / 2) / x_size, (y - row_height / 2) / y_size, str(value),
                horizontalalignment='center',
                verticalalignment='center',
                transform=ax.transAxes,
                fontsize=10)

ax.set_xlim(0, 0.944)  # 假设图片是100x100像素
ax.set_ylim(0, 0.551)
ax.set_aspect('equal')
# 隐藏坐标轴
# ax.axis('off')

# 显示图形
plt.show()
